import { useEffect, useState } from 'react'
import Taro, { FC } from '@tarojs/taro'
import { AtRadio } from 'taro-ui'
import { Subject, Subscription } from 'rxjs'
import { debounceTime, map, switchMap, tap } from 'rxjs/operators'
import { View, Text, Button } from '@tarojs/components'
import "taro-ui/dist/style/components/button.scss" // 按需引入 
import "taro-ui/dist/style/components/radio.scss";
import "taro-ui/dist/style/components/icon.scss";

import { useRoomDataFacade } from '@/hooks/useRoomDataFacade'
import { EditRoomParams } from '@/models/request/roomReq'
import { onEmit } from '@/utils/rxHelpers'
import { getLogger } from '@/utils/log'
import { MUTE_STATUS, } from '@/constants/room'

import './index.scss'

//评论设置
export const ChatSetting: FC = () => {

  const logger = getLogger("/pages/liveRoom/chatSettings");
  const [roomFacade,
    roomRole,
    roomStatus,
    type,
    ownerId,
    anchorId,
    assistants,
    liveStreams,
    linkStreams,
    ui_muted,
    ui_debug,
    ui_isFront,
    ui_mode,
    ui_beauty,
    ui_operation,
    muteStatus] = useRoomDataFacade();

  const initSubject = () => new Subject<any>();
  // 初始化按钮接收参数subject
  const [emitter, setEmitter] = useState(initSubject);

  const [status, setStatus] = useState(muteStatus.toString());
  const [select, setSelect] = useState(MUTE_STATUS.NORMAL);

  const handleChange = (value) => {
    setSelect(parseInt(value))
    setStatus(value)
    console.log('选中的值：', value)
  }

  //把按钮点击事件转化为observable
  const editLive$ = emitter.asObservable()
    .pipe(
      //防抖动(防重复)
      debounceTime(500),
      map(obj => obj as EditRoomParams),
      //接收按钮点击的参数
      tap(editLiveObj => {
        console.log("editLiveObj:", editLiveObj)
        if (editLiveObj.muteStatus !== MUTE_STATUS.NORMAL && editLiveObj.muteStatus !== MUTE_STATUS.BANNED && editLiveObj.muteStatus !== MUTE_STATUS.PENDING) {
          throw Taro.showToast({
            title: '评论状态值异常',
            icon: 'none',
            duration: 2000
          })
        }
      }),
      switchMap(roomFacade.editRoomChat)
    )

  useEffect(() => {
    //注册并执行所有rxjs流
    const subscriptions: Subscription[] = [
      onEmit<string>(
        editLive$,
        () => Taro.showToast({
          title: '保存成功',
          icon: 'none',
          duration: 2000
        }),
        err => {
          logger.ERROR("保存信息失败！", err)
          setEmitter(initSubject);
        }
      ),

    ]
    //页面销毁时也销毁所有订阅，防止内存泄漏
    return () => { subscriptions.map(sub => sub.unsubscribe()) };

  }, [])

  //观察muteStatus
  useEffect(() => {
    setStatus(muteStatus.toString())
  }, [muteStatus])

  return (
    <View className='index'>
      <View className='main'>
        <AtRadio
          options={[
            { label: '开启发言', value: "0", desc: '所有观众可以发言，有良好的敏感词屏蔽。' },
            { label: '全局禁言', value: "1", desc: '只有管理员能发言' },
            { label: '先审后发', value: "2", desc: '所有观众可以发言，但需要主播在聊天中审核后在共屏展示' }
          ]}
          value={status}
          onClick={handleChange.bind(this)}
        />
      </View>
      <Button className='bt' onClick={() => emitter.next({
        muteStatus: select
      } as EditRoomParams)}
      >
        <Text className='text'>保存</Text>
      </Button>
    </View>
  )
}
export default ChatSetting